package com.endoc.endocbtool;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;

import android.content.Intent;
import android.os.Bundle;

import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.endoc.base.BaseActivity;
import com.endoc.base.adapter.SimpleBaseBindingAdapter;
import com.endoc.base.utils.AESUtil;
import com.endoc.base.utils.BitFieldUtils;
import com.endoc.base.utils.LogUtils;
import com.endoc.base.utils.Utils;
import com.endoc.btmodule.DataUtils;
import com.endoc.endocbtool.bean.JCLBean;
import com.endoc.endocbtool.databinding.ActivityMainBinding;
import com.endoc.endocbtool.databinding.BufaItemBinding;
import com.endoc.endocbtool.databinding.DeviceItemBinding;
import com.endoc.endocbtool.viewmodel.MainViewModel;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import pub.devrel.easypermissions.EasyPermissions;

import static cn.com.heaton.blelibrary.ble.Ble.REQUEST_ENABLE_BT;

public class MainActivity extends BaseActivity<MainViewModel, ActivityMainBinding> {
    String TAG = "MainActivity";
    private static final int RC_LOCATION_GPS_PREM = 124;
    private static final String[] BLE = {Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION};
    private SimpleBaseBindingAdapter<BleDevice, DeviceItemBinding> mSimpleBaseBindingAdapter;
    //private SimpleBaseBindingAdapter<JCLBean, JclLayoutBinding> mLjlSimpleBaseBindingAdapter;

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }


    public class Click {
        String key = "1111111111111111";
        public void keepBind() {
            cal = Calendar.getInstance();
            byte data[] = BitFieldUtils.biteFieldToByteArray("13612874251");
            byte bind[] = new byte[19];
            bind[0] = 0x7e;
            bind[1] = 0x14;
            bind[2] = 0x10;
            byte jiaMi[] = new byte[16];
            jiaMi[0] = 0x53;
            jiaMi[1] = 0x54;
            jiaMi[2] = (byte) (int) Integer.valueOf(Integer.valueOf(cal.get(Calendar.YEAR)).toString().substring(2));
            jiaMi[3] = (byte) (cal.get(Calendar.MONTH) + 1);
            jiaMi[4] = (byte) cal.get(Calendar.DAY_OF_MONTH);
            jiaMi[5] = (byte) (cal.get(Calendar.HOUR_OF_DAY));
            jiaMi[6] = (byte) (cal.get(Calendar.MINUTE));
            jiaMi[7] = (byte) cal.get(Calendar.SECOND);
            jiaMi[8] = (byte) cal.get(Calendar.MILLISECOND);
            jiaMi[9] = (byte) (cal.get(Calendar.MILLISECOND) >> 8);
            jiaMi[10] = data[0];
            jiaMi[11] = data[1];
            jiaMi[12] = data[2];
            jiaMi[13] = data[3];
            jiaMi[14] = data[4];
            jiaMi[15] = data[5];
            LogUtils.LogD(TAG, DataUtils.bytesToHexString(jiaMi, jiaMi.length));
            //执行加密
            byte[] encrypt = AESUtil.encrypt(jiaMi, key);
            //执行解密
            byte[] decrypt = AESUtil.decrypt(encrypt, key);
            LogUtils.LogD(TAG, "解密数据==" + DataUtils.bytesToHexString(decrypt, decrypt.length));
            System.arraycopy(encrypt, 0, bind, 3, encrypt.length);
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bind);
        }

        public void previousKeepConnect() {
            byte data[] = BitFieldUtils.biteFieldToByteArray("13612874251");
            byte bind[] = new byte[19];
            bind[0] = 0x7e;
            bind[1] = 0x14;
            bind[2] = 0x10;
            byte jiaMi[] = new byte[16];
            jiaMi[0] = 0x53;
            jiaMi[1] = 0x54;
            jiaMi[2] = (byte) (int) Integer.valueOf(Integer.valueOf(cal.get(Calendar.YEAR)).toString().substring(2));
            jiaMi[3] = (byte) (cal.get(Calendar.MONTH) + 1);
            jiaMi[4] = (byte) cal.get(Calendar.DAY_OF_MONTH);
            jiaMi[5] = (byte) (cal.get(Calendar.HOUR_OF_DAY));
            jiaMi[6] = (byte) (cal.get(Calendar.MINUTE));
            jiaMi[7] = (byte) cal.get(Calendar.SECOND);
            jiaMi[8] = (byte) cal.get(Calendar.MILLISECOND);
            jiaMi[9] = (byte) (cal.get(Calendar.MILLISECOND) >> 8);
            jiaMi[10] = data[0];
            jiaMi[11] = data[1];
            jiaMi[12] = data[2];
            jiaMi[13] = data[3];
            jiaMi[14] = data[4];
            jiaMi[15] = data[5];
            LogUtils.LogD(TAG, DataUtils.bytesToHexString(jiaMi, jiaMi.length));
            //执行加密
            byte[] encrypt = AESUtil.encrypt(jiaMi, key);
            //执行解密
            byte[] decrypt = AESUtil.decrypt(encrypt, key);
            LogUtils.LogD(TAG, "解密数据==" + DataUtils.bytesToHexString(decrypt, decrypt.length));
            System.arraycopy(encrypt, 0, bind, 3, encrypt.length);
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bind);
        }

        public void unbind() {
            byte data[] = BitFieldUtils.biteFieldToByteArray("13612874251");
            Calendar cal = Calendar.getInstance();
            byte bind[] = new byte[19];
            bind[0] = 0x7e;
            bind[1] = 0x12;
            bind[2] = 0x10;
            byte jiaMi[] = new byte[16];
            jiaMi[0] = 0x53;
            jiaMi[1] = 0x54;
            jiaMi[2] = (byte) (int) Integer.valueOf(Integer.valueOf(cal.get(Calendar.YEAR)).toString().substring(2));
            jiaMi[3] = (byte) (cal.get(Calendar.MONTH) + 1);
            jiaMi[4] = (byte) cal.get(Calendar.DAY_OF_MONTH);
            jiaMi[5] = (byte) (cal.get(Calendar.HOUR_OF_DAY));
            jiaMi[6] = (byte) (cal.get(Calendar.MINUTE));
            jiaMi[7] = (byte) cal.get(Calendar.SECOND);
            jiaMi[8] = (byte) cal.get(Calendar.MILLISECOND);
            jiaMi[9] = (byte) (cal.get(Calendar.MILLISECOND) >> 8);
            jiaMi[10] = data[0];
            jiaMi[11] = data[1];
            jiaMi[12] = data[2];
            jiaMi[13] = data[3];
            jiaMi[14] = data[4];
            jiaMi[15] = data[5];
            LogUtils.LogD(TAG, DataUtils.bytesToHexString(jiaMi, jiaMi.length));
            //执行加密
            byte[] encrypt = AESUtil.encrypt(jiaMi, key);
            //执行解密
            byte[] decrypt = AESUtil.decrypt(encrypt, key);
            LogUtils.LogD(TAG, "解密数据==" + DataUtils.bytesToHexString(decrypt, decrypt.length));
            System.arraycopy(encrypt, 0, bind, 3, encrypt.length);
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bind);
        }

        public void qzunbind() {
            byte qzunbind[] = {0x7e, 0x13, 0x06, 1, 2, 3, 4, 5};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), qzunbind);
        }

        Calendar cal;

        public void bind(View view) {
            cal = Calendar.getInstance();
            byte data[] = BitFieldUtils.biteFieldToByteArray("13612874251");
            byte bind[] = new byte[19];
            bind[0] = 0x7e;
            bind[1] = 0x11;
            bind[2] = 0x10;
            byte jiaMi[] = new byte[16];
            jiaMi[0] = 0x53;
            jiaMi[1] = 0x54;
            jiaMi[2] = (byte) (int) Integer.valueOf(Integer.valueOf(cal.get(Calendar.YEAR)).toString().substring(2));
            jiaMi[3] = (byte) (cal.get(Calendar.MONTH) + 1);
            jiaMi[4] = (byte) cal.get(Calendar.DAY_OF_MONTH);
            jiaMi[5] = (byte) (cal.get(Calendar.HOUR_OF_DAY));
            jiaMi[6] = (byte) (cal.get(Calendar.MINUTE));
            jiaMi[7] = (byte) cal.get(Calendar.SECOND);
            jiaMi[8] = (byte) cal.get(Calendar.MILLISECOND);
            jiaMi[9] = (byte) (cal.get(Calendar.MILLISECOND) >> 8);
            jiaMi[10] = data[0];
            jiaMi[11] = data[1];
            jiaMi[12] = data[2];
            jiaMi[13] = data[3];
            jiaMi[14] = data[4];
            jiaMi[15] = data[5];
            LogUtils.LogD(TAG, DataUtils.bytesToHexString(jiaMi, jiaMi.length));
            //执行加密
            byte[] encrypt = AESUtil.encrypt(jiaMi, key);
            //执行解密
            byte[] decrypt = AESUtil.decrypt(encrypt, key);
            LogUtils.LogD(TAG, "解密数据==" + DataUtils.bytesToHexString(decrypt, decrypt.length));
            System.arraycopy(encrypt, 0, bind, 3, encrypt.length);
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bind);
        }

        public void djl() {
            int djlBytes = Integer.parseInt(viewModel.djlMutableLiveData.getValue().trim());
            byte djlxz[] = {0x7e, 0x31, 1, (byte) djlBytes};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), djlxz);
        }

        public void djlsz() {
            int djlszBytes = (int) (Float.parseFloat(viewModel.djlszMutableLiveData.getValue().trim()) * 10);
            byte djlxz[] = {0x7e, 0x21, 2, (byte) djlszBytes, (byte) (djlszBytes >> 8)};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), djlxz);
        }

        public void rzl() {
            String rzl = viewModel.rzlMutableLiveData.getValue();
            int i = Integer.parseInt(rzl);
            byte djlxz[] = {0x7e, 0x32, 2, (byte) i, (byte) (i >> 8)};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), djlxz);
        }

        public void ydscj() {
            String ydscj = viewModel.ydscjMutableLiveData.getValue();
            int i = Integer.parseInt(ydscj);
            byte ydscji[] = {0x7e, 0x33, 1, (byte) i};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), ydscji);
        }

        public void bjlx() {
            String bjlx = viewModel.bjlxMutableLiveData.getValue();
            int i = Integer.parseInt(bjlx);
            byte bjlei[] = {0x7e, 0x34, 1, (byte) i};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bjlei);
        }

        public void fangbo() {
            //byte[] bytes = DecimalFormatUtils.floatToByte(viewModel.fbMutableLiveData.getValue());
            int fb = (int) (Float.parseFloat(viewModel.fbMutableLiveData.getValue()) * 10);
            String fbTime = viewModel.fbTimeMutableLiveData.getValue();
            int fbTimei = Integer.parseInt(fbTime);
            byte fbi[] = {0x7e, 0x22, 3, (byte) fb, (byte) (fb >> 8), (byte) fbTimei};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), fbi);
        }

        public void qxfangbo() {
            byte qxfb[] = {0x7e, 0x23, 1, 1};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), qxfb);
        }

        public void shuangbo() {
            //byte[] fbBytes = DecimalFormatUtils.floatToByte(viewModel.fbMutableLiveData.getValue());
            int fb = (int) (Float.parseFloat(viewModel.fbMutableLiveData.getValue()) * 10);
            String fbTime = viewModel.fbTimeMutableLiveData.getValue();
            int fbTimei = Integer.parseInt(fbTime);
            //byte[] djlBytes = DecimalFormatUtils.floatToByte(viewModel.djlMutableLiveData.getValue());
            int djlBytes = (int) (Float.parseFloat(viewModel.djlszMutableLiveData.getValue()) * 10);
            byte shuangbo[] = {0x7e, 0x24, 5, (byte) djlBytes, (byte) (djlBytes >> 8), (byte) fb, (byte) (fb >> 8), (byte) fbTimei};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), shuangbo);
        }

        public void qxshuangbo() {
            byte[] qxshuangbo = {0x7e, 0x25, 0x01, 1};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), qxshuangbo);
        }

        public void paiqi() {
            byte parseFloat = (byte) (Float.parseFloat(viewModel.paiqiMutableLiveData.getValue()) * 10);

            byte[] paiqi = {0x7e, 0x26, 0x01, parseFloat};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), paiqi);
        }

        public void lgfw() {
            byte[] lgfw = {0x7e, 0x27, 0x01, 11};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), lgfw);
        }

        public void bhszkq() {
            byte[] bhszkq = {0x7e, 0x28, 1, 1};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bhszkq);
        }

        public void bhszgb() {
            byte[] bhszgb = {0x7e, 0x28, 1, 0};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bhszgb);
        }

        public void yxsz() {
            byte[] yxsz = {0x7e, 0x2A, 1, 1};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), yxsz);
        }

        public void ztsz() {
            byte[] ztsz = {0x7e, 0x2A, 1, 0};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), ztsz);
        }

        public void bhjl() {
            int b = (int) (Float.parseFloat(viewModel.bhjlMutableLiveData.getValue()));
            byte[] bhjl = {0x7e, 0x29, 2, (byte) b, (byte) (b >> 8)};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), bhjl);
        }


        public void gxsj() {
            byte gxsj[] = {0x7e, 0x30, 0x06, (byte) Integer.parseInt(viewModel.updateTimeYearMutableLiveData.getValue()), (byte) Integer.parseInt(viewModel.updateTimeMouthMutableLiveData.getValue()), (byte) Integer.parseInt(viewModel.updateTimeDayMutableLiveData.getValue()), (byte) Integer.parseInt(viewModel.updateTimeHourMutableLiveData.getValue()), (byte) Integer.parseInt(viewModel.updateTimeMinMutableLiveData.getValue()), (byte) Integer.parseInt(viewModel.updateTimeMiaoMutableLiveData.getValue())};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), gxsj);
        }

        public void gxdqsj() {
            byte gxdqsj[] = new byte[8];
            Calendar cal = Calendar.getInstance();
            gxdqsj[0] = 0x7e;
            gxdqsj[1] = 0x30;
            gxdqsj[2] = 0x06;
            gxdqsj[3] = (byte) (int) Integer.valueOf(Integer.valueOf(cal.get(Calendar.YEAR)).toString().substring(2));
            gxdqsj[4] = (byte) (cal.get(Calendar.MONTH) + 1);
            gxdqsj[5] = (byte) cal.get(Calendar.DAY_OF_MONTH);
            gxdqsj[6] = (byte) (cal.get(Calendar.HOUR_OF_DAY));
            gxdqsj[7] = (byte) (cal.get(Calendar.MINUTE));
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), gxdqsj);
            //viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(),gxdqsj,UUID.fromString("0000fE40-0000-1000-8000-00805f9b34fb"),UUID.fromString("0000FE41-0000-1000-8000-00805f9b34fb"));
        }

        public void jcl() {
            int jcl = (int) (Float.parseFloat(viewModel.simpleJclBeanMutableLiveData.getValue()) * 100);
            byte jclData[] = new byte[52];
            jclData[0] = 0x7e;
            jclData[1] = 0x35;
            jclData[2] = 49;
            jclData[3] = 24;
            for (int i = 4; i < jclData.length; i++) {
                jclData[i] = i % 2 == 0 ? (byte) jcl : (byte) (jcl >> 8);
            }
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), jclData);


        }

        public void fejcl() {
            int jcl = (int) (Float.parseFloat(viewModel.simpleJclBeanMutableLiveData.getValue()) * 100);
            byte fejclData[] = new byte[99];
            fejclData[0] = 0x7e;
            fejclData[1] = 0x35;
            fejclData[2] = 97;
            fejclData[3] = 48;
            for (int i = 4; i < fejclData.length; i++) {
                fejclData[i] = i % 2 == 0 ? (byte) jcl : (byte) (jcl >> 8);
            }
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), fejclData);
        }

        public void lSJCL() {
            byte lSJCLData[] = new byte[5];
            lSJCLData[0] = 0x7e;
            lSJCLData[1] = 0x36;
            lSJCLData[2] = 2;
            lSJCLData[3] = (byte) Integer.parseInt(viewModel.lsJclMutableLiveData.getValue());
            lSJCLData[4] = (byte) Integer.parseInt(viewModel.lsJclZSMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), lSJCLData);
        }

        public void cancellSJCL() {
            byte cancellSJCLData[] = new byte[5];
            cancellSJCLData[0] = 0x7e;
            cancellSJCLData[1] = 0x37;
            cancellSJCLData[2] = 1;
            cancellSJCLData[3] = 1;
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), cancellSJCLData);
        }

        //日总量时间
        public void rzlTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    //Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                    viewModel.rzlTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //日总量补发
        public void rzlBuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.rzlNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.rzlTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x42, 0x0d, 2, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0, 0});
        }

        //排气时间
        public void pqTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    //Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                    viewModel.pqTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //排气补发
        public void pqBuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.pqNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.pqTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x42, 0x0d, 3, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0, 0});
        }


        //基础率24时间
        public void jcl24Time() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    //Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                    viewModel.jcl24TimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //基础率24补发
        public void jcl24BuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.jcl24NumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.jcl24TimerMutableLiveData.getValue());
            byte sendData[] = new byte[62];
            sendData[0] = 0x7e;
            sendData[1] = 0x44;
            //sendData[2]= (byte) (data.size()+11);
            sendData[2] = 0x3b;//59
            sendData[3] = numberBytes[0];
            sendData[4] = numberBytes[1];
            sendData[5] = numberBytes[2];
            sendData[6] = numberBytes[3];
            sendData[7] = calendarBytes[0];
            sendData[8] = calendarBytes[1];
            sendData[9] = calendarBytes[2];
            sendData[10] = calendarBytes[3];
            sendData[11] = calendarBytes[4];
            sendData[12] = calendarBytes[5];
            sendData[13] = 24;
        /*for (int i = 0; i < 24; i++) {
            sendData[i * 2 + 14] = (byte) data[i];
            sendData[i * 2 + 15] = (byte) (data[i] >> 8);
        }*/
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), sendData);
        }


        //基础率48时间
        public void jcl48Time() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    //Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                    viewModel.jcl48TimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //基础率48补发
        public void jcl48BuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.jcl48NumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.jcl48TimerMutableLiveData.getValue());
            byte sendData[] = new byte[0x6e];
            sendData[0] = 0x7e;
            sendData[1] = 0x44;
            //sendData[2]= (byte) (data.size()+11);
            sendData[2] = 0x6B;//59
            sendData[3] = numberBytes[0];
            sendData[4] = numberBytes[1];
            sendData[5] = numberBytes[2];
            sendData[6] = numberBytes[3];
            sendData[7] = calendarBytes[0];
            sendData[8] = calendarBytes[1];
            sendData[9] = calendarBytes[2];
            sendData[10] = calendarBytes[3];
            sendData[11] = calendarBytes[4];
            sendData[12] = calendarBytes[5];
            sendData[13] = 48;
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), sendData);
        }


        //报警时间
        public void alarmTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    //Toast.makeText(MainActivity.this, getTime(date), Toast.LENGTH_SHORT).show();
                    viewModel.alarmTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //报警补发
        public void alarmBuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.alarmNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.alarmTimerMutableLiveData.getValue());
            byte alarmData[] = {0x7e, 0x46, 0x0c, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0, 0};
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), alarmData);
        }


        //胰岛素厂家时间
        public void insulinTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    viewModel.insulinTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //胰岛素厂家补发
        public void insulinBuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.insulinNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.insulinTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x4A, 0x0B, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0});
        }


        //螺杆复位时间
        public void lgfwTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    viewModel.lgfwTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //螺杆复位补发
        public void lgfwBuFa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.lgfwNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.lgfwTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x4c, 0x0c, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5]});

        }

        //大剂量时间
        public void djlTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    viewModel.danBoTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //大剂量补发
        public void djlBufa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.danBoNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.danBoTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x48, 0x0d, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], 1, calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0, 0});
        }

        //方波时间
        public void fangBoTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    viewModel.fangBoTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //方波补发
        public void fangBoBufa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.fangBoNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.fangBoTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x48, 0x0e, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], 2, calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0, 0, 0});
        }

        //双波时间
        public void shuangBoTime() {
            new TimePickerBuilder(MainActivity.this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    viewModel.shuangBoTimerMutableLiveData.setValue(date.getTime());
                }
            }).build().show();
        }

        //双波补发
        public void shuangBoBufa() {
            byte[] numberBytes = Utils.getNumberBytes(Integer.parseInt(viewModel.shuangBoNumberMutableLiveData.getValue()));
            byte[] calendarBytes = Utils.getCalendarBytes(viewModel.shuangBoTimerMutableLiveData.getValue());
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, 0x48, 0x10, numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3], 3, calendarBytes[0], calendarBytes[1], calendarBytes[2], calendarBytes[3], calendarBytes[4], calendarBytes[5], 0, 0, 0, 0, 0});
        }

        //重命名补发
        public void rename() {
            char[] rename = viewModel.reNameMutableLiveData.getValue().toCharArray();
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0xe1, 0x06, (byte) rename[0], (byte) rename[1], (byte) rename[2], (byte) rename[3], (byte) rename[4], (byte) rename[5]});
        }

        //打药补发
        public void daYa() {
            byte[] numberBytes = Utils.getNumberBytes(Long.parseLong(viewModel.dybfLiveData.getValue()));
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x71, 0x0e,numberBytes[0], numberBytes[1], numberBytes[2], numberBytes[3],0,0,0,0,0,0,0,0});
        }

        //泵状态查询
        public void bengStatus() {
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x60,0});
        }

        //大剂量限制
        public void djlXZ() {
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x61,0});
        }
        //日总量限制
        public void rzlXZ() {
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x62,0});
        }
        //报警类型设置
        public void bjlXZ(){
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x63,0});
        }
        //输注确认
        public void szQR(){
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x90,1,1});
        }
        //输注速度慢
        public void szSDM(){
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x91,1,2});
        }
        //输注速度快
        public void szSDK(){
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x91,1,1});
        }
        //查询所有最新数据
        public void cxNewsData(){
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e, (byte) 0x67,1,1});
        }
        //启动时间序号
        public void qdsjxh() {
            viewModel.bleModel.writeData(viewModel.connectDeviceLiveData.getValue(), new byte[]{0x7e,0x66,1,1});
        }

    }
    RecyclerView recyclerView;//补发过程中显示的内容
    SimpleBaseBindingAdapter<String, BufaItemBinding> objectViewDataBindingSimpleBaseBindingAdapter;
    PopupWindow pupWindow;


    public void showWindow() {
        if(pupWindow==null||!pupWindow.isShowing()){
            LayoutInflater la = LayoutInflater.from(MainActivity.this);
            View view = la.inflate(R.layout.pupwindow, null);//自定义布局
            recyclerView = (RecyclerView)view.findViewById(R.id.rv_show);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(linearLayoutManager);
            objectViewDataBindingSimpleBaseBindingAdapter = new SimpleBaseBindingAdapter<String, BufaItemBinding>(mActivity,R.layout.bufa_item) {

                @Override
                protected void onSimpleBindItem(BufaItemBinding binding, String item, RecyclerView.ViewHolder holder) {
                            binding.etShow.setText(item);
                }
            };
            recyclerView.setAdapter(objectViewDataBindingSimpleBaseBindingAdapter);
            pupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, 600);
            //设置PopupWindow的焦点
            pupWindow.setFocusable(true);
            //点击PopupWindow之外的地方PopupWindow会消失
            pupWindow.setOutsideTouchable(true);
            //showAtLocation(View parent, int gravity, int x, int y)：相对于父控件的位置（例如正中央Gravity.CENTER，下方Gravity.BOTTOM等），可以设置偏移或无偏移
            pupWindow.showAtLocation(MainActivity.this.getWindow().getDecorView(), Gravity.TOP, 0, 0);
            pupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    viewModel.originMutableLiveData.getValue().clear();
                }
            });
        }
        objectViewDataBindingSimpleBaseBindingAdapter.setList(viewModel.originMutableLiveData.getValue());
        objectViewDataBindingSimpleBaseBindingAdapter.notifyDataSetChanged();
        pupWindow.update();
    }


    @Override
    public MainViewModel getViewModel() {
        return getActivityViewModelProvider(this).get(MainViewModel.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        dataBinding.rvDeviceItem.setLayoutManager(linearLayoutManager);
        //设置适配器
        mSimpleBaseBindingAdapter = new SimpleBaseBindingAdapter<BleDevice, DeviceItemBinding>(this, R.layout.device_item) {

            /**
             * @param binding 当前条目的dataBinding对象
             * @param item  条目数据对象
             * @param holder  holder
             */
            @Override
            protected void onSimpleBindItem(DeviceItemBinding binding, BleDevice item, RecyclerView.ViewHolder holder) {
                binding.setDevice(item);
                binding.btConnect.setOnClickListener(v -> {
                    if (!item.isConnected()) {

                        //BleTools.connectBle(item);
                        viewModel.bleModel.connectBle(item);
                    } else {
                        viewModel.bleModel.disconnectBle(item);
                    }
                });
            }


        };
        //设置数据
        mSimpleBaseBindingAdapter.setList(viewModel.scanDeviceListMutableLiveData.getValue());
        dataBinding.rvDeviceItem.setAdapter(mSimpleBaseBindingAdapter);


        //设计基础率
       /* LinearLayoutManager jclLinearLayoutManager = new LinearLayoutManager(this);
        jclLinearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        dataBinding.rvJcl.setLayoutManager(jclLinearLayoutManager);
        //设置适配器
        mLjlSimpleBaseBindingAdapter = new SimpleBaseBindingAdapter<JCLBean,JclLayoutBinding>(this, R.layout.jcl_layout) {

            @Override
            protected void onSimpleBindItem(JclLayoutBinding binding, JCLBean item, RecyclerView.ViewHolder holder) {
                binding.setVm(item);

            }
        };

        //设置数据
        mLjlSimpleBaseBindingAdapter.setList(viewModel.jclBeanMutableLiveData.getValue());
        dataBinding.rvJcl.setAdapter(mLjlSimpleBaseBindingAdapter);*/

        dataBinding.setClick(new Click());

    }


    @Override
    public void initLiveData() {
        //创建蓝牙相关viewModel
        //new BleRegisterViewModel(this,this,viewModel);
        //BleTools.setIBleCallBack(this);//初始化蓝牙回调接口
        dataBinding.setVm(viewModel);//设置dataBinding的数据,否则databinding没有数据源
        viewModel.initScanDeviceList();
        List<JCLBean> jclBeans = new ArrayList<>();
        JCLBean jclBean;

        for (int i = 0; i < 24; i++) {
            jclBean = new JCLBean();
            jclBean.number = i + 1 + "";
            jclBean.jcl = "";
            jclBeans.add(jclBean);
        }
        viewModel.jclBeanMutableLiveData.setValue(jclBeans);


        viewModel.deviceListVisibleLiveData.setValue(View.VISIBLE);
        viewModel.djlMutableLiveData.observe(this, s -> Log.d(TAG, "大剂量输入的值" + s));

        viewModel.scanDeviceListMutableLiveData.observe(this, list -> {
            LogUtils.LogD(TAG, "集合收到数据:" + list.size());
            mSimpleBaseBindingAdapter.setList(list);
            mSimpleBaseBindingAdapter.notifyDataSetChanged();
        });
        viewModel.connectDeviceLiveData.observe(this, bleDevice -> {
            //设备连接状态改变,那么就更新ui,因为是recycleView,所以单独更改不好实现,直接全部更新
            mSimpleBaseBindingAdapter.notifyDataSetChanged();
            dataBinding.tvDeviceName.setText(bleDevice.getBleName());
        });
        viewModel.originMutableLiveData.observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> strings) {
                showWindow();
            }
        });


    }

    @Override
    public void initOperation() {
        checkBle();
    }

    public void startSearch() {
        if (EasyPermissions.hasPermissions(mActivity, BLE)) {
            viewModel.bleModel.scanBle();
        } else {
            EasyPermissions.requestPermissions(MainActivity.this,
                    "权限拒绝,请开启权限",//使用官方提供的弹窗(`AppSettingsDialog`)的时候会用到这个字符串,作为用户拒绝之后弹窗的内容
                    RC_LOCATION_GPS_PREM,
                    BLE);
        }
    }


    /*检查蓝牙是否支持及打开*/
    @SuppressLint("MissingPermission")
    private void checkBle() {
        Log.d(TAG, "checkBle");
        // 检查设备是否支持BLE4.0

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        // 初始化蓝牙适配器. API版本必须是18以上, 通过 BluetoothManager 获取到BLE的适配器.

        // 检查当前的蓝牙设别是否支持.
        if (adapter == null) {
            Toast.makeText(mActivity, "不支持Ble蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!adapter.isEnabled()) {
            Log.d(TAG, "checkBle提示打开蓝牙");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            startSearch();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Log.d(TAG,"Activity.RESULT_OK");
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) {
            startSearch();
        } else if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将结果交由EasyPermissions解决
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == RC_LOCATION_GPS_PREM) {
            startSearch();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

}
